package kr.co.nextree.android.sample.activity;

import kr.co.nextree.android.sample.R;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class ViewFlipperSample extends Activity implements View.OnTouchListener, CompoundButton.OnCheckedChangeListener {
	private CheckBox checkBox; 
	private ViewFlipper flipper;
    private Button mOpenBtn;
    private LinearLayout mViewerLayout;
    private LinearLayout mDotViewer;
    
    // 터치 이벤트 발생 지점의 x좌표 저장
    float xAtDown;
    float xAtUp;
    
    private boolean isStart;
    
    private static final int FLIP_INTERVAL = 3000;
    private static final int SHOW_NEXT = 0;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		   setContentView(R.layout.view_flipper);
		   
		   mViewerLayout = (LinearLayout)findViewById(R.id.viewerLayout);
		   mDotViewer = (LinearLayout)findViewById(R.id.dotViewer);
	        
	       checkBox = (CheckBox)findViewById(R.id.chkAuto);
	       checkBox.setOnCheckedChangeListener(this);
	        
	       flipper = (ViewFlipper)findViewById(R.id.viewFlipper);
	       flipper.setOnTouchListener(this);
	       
	       //LinearLayout linear;//서랍처럼 쓸 layout
	       //x좌표 변동 없이 맨아래 WINDOW_HEIGHT에서 맨위 0까지 움직이는 애니메이션
	       //TranslateAnimation ta = new TranslateAnimation(0,0,0,0);
	       //ta.setDuration(2000);//2초만에 움직이기
	       //mViewerLayout.setAnimation(ta);//linear layout에 ta애니 적용..
	       
	       
	        
	       // ViewFlipper에 동적으로 child view 추가
/*	       TextView tv = new TextView(this);
	       tv.setText("View 4\nDynamically added");
	       tv.setTextColor(Color.CYAN);
	       flipper.addView(tv);    */   
	        
	       
/*	       mViewerLayout.setInAnimation(AnimationUtils.loadAnimation(this,
		        	R.anim.push_left_in));
	       mViewerLayout.setOutAnimation(AnimationUtils.loadAnimation(this,
	    		   R.anim.push_left_out));*/
	        
	       mOpenBtn = (Button)findViewById(R.id.openBtn);
	       mOpenBtn.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(mViewerLayout.getVisibility() ==  View.VISIBLE) {
						mViewerLayout.setVisibility(View.GONE);
					} else {
						mViewerLayout.setVisibility(View.VISIBLE);
					}
					
				}
			});
	        
	        int imageCnt = flipper.getChildCount();
	        int currentImgIndex = flipper.getDisplayedChild();
	        
	        for(int i=0; i < imageCnt; i++) {
	        	ImageView dotImage = new ImageView(this);
		        dotImage.setBackgroundResource(R.drawable.dot_off);
		        dotImage.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
	        	mDotViewer.addView(dotImage);
	        }
	        
	        mDotViewer.getChildAt(currentImgIndex).setBackgroundResource(R.drawable.dot_on);
	}
	

    // View.OnTouchListener의 abstract method
    // flipper 터지 이벤트 리스너
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// 터치 이벤트가 일어난 뷰가 ViewFlipper가 아니면 return
		if(v != flipper) return false;		
		
		if(event.getAction() == MotionEvent.ACTION_DOWN) {
			xAtDown = event.getX(); // 터치 시작지점 x좌표 저장			
		} else if(event.getAction() == MotionEvent.ACTION_UP){
			xAtUp = event.getX(); 	// 터치 끝난지점 x좌표 저장
			
			if( xAtUp < xAtDown ) {
				// 왼쪽 방향 에니메이션 지정
				flipper.setInAnimation(AnimationUtils.loadAnimation(this,
		        		R.anim.push_left_in));
		        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
		        		R.anim.push_left_out));
		        		
		        // 다음 view 보여줌
		        mDotViewer.getChildAt(flipper.getDisplayedChild()).setBackgroundResource(R.drawable.dot_off);
				flipper.showNext();
				mDotViewer.getChildAt(flipper.getDisplayedChild()).setBackgroundResource(R.drawable.dot_on);
			} else if (xAtUp > xAtDown){
				// 오른쪽 방향 에니메이션 지정
				flipper.setInAnimation(AnimationUtils.loadAnimation(this,
		        		R.anim.push_right_in));
		        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
		        		R.anim.push_right_out));
		        // 전 view 보여줌
		        mDotViewer.getChildAt(flipper.getDisplayedChild()).setBackgroundResource(R.drawable.dot_off);
				flipper.showPrevious();	
				mDotViewer.getChildAt(flipper.getDisplayedChild()).setBackgroundResource(R.drawable.dot_on);
			}
		}	
		return true;
	}

	// CompoundButton.OnCheckedChangeListener의 abstract method
	// 책크박스 책크 이벤트 리스너
	@Override
	public void onCheckedChanged(CompoundButton view, final boolean isChecked) {
		
		Log.w("checked", Boolean.toString(isChecked));
		
		if(isChecked == true) {
			// 왼쪽 에니메이션 설정
			flipper.setInAnimation(AnimationUtils.loadAnimation(this,
	        		R.anim.push_left_in));
	        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
	        		R.anim.push_left_out));
			
	        // 자동 Flipping 시작 (간격 3초)
			//flipper.setFlipInterval(3000);
			//flipper.startFlipping();
			
			isStart = true;
		} else {
			// 자동 Flipping 해지
			//flipper.stopFlipping();
			isStart = false;
		}	
		
		new Thread(new AtuoImagesFlipperRunner()).start(); 
	}
   
   private class AtuoImagesFlipperRunner implements Runnable{ 
	   
       @Override 
       public void run() { 
            while(isStart){ 
                 Message m = new Message(); 
                 m.what = SHOW_NEXT; 
                 myViewUpdateHandler.sendMessage(m); 
                 try { 
                      Thread.sleep(FLIP_INTERVAL); 
                 } catch (InterruptedException e) { } 
            } 
       } 
  }
   
	
   Handler myViewUpdateHandler = new Handler(){ 
       // @Override 
       public void handleMessage(Message msg) { 
            switch (msg.what) { 
                 case SHOW_NEXT: 
                	 mDotViewer.getChildAt(flipper.getDisplayedChild())
						.setBackgroundResource(R.drawable.dot_off);
                	 
                	 flipper.showNext();
                	 
                	 mDotViewer.getChildAt(flipper.getDisplayedChild())
						.setBackgroundResource(R.drawable.dot_on);
                      break; 
            } 
            super.handleMessage(msg); 
       } 
  }; 

}
